<?php
class SignsController extends AppController {

	var $name = 'Signs';
	var $uses = array('PeopleSign','Sign');

    function beforeFilter () {
        parent::beforeFilter();

		// Aplico el Layout segun la Vista o si es AJAX
		if ($this->RequestHandler->isAjax()) {
			$this->layout = 'ajax';
		}else{
			// Cambio la Vista por la del Rol
			$this->layout = strtolower($this->Session->read('VistaActual'));
		}
    }
    
	function index() {
		$this->Sign->recursive = 0;
		$this->set('signs', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid sign', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('sign', $this->Sign->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Sign->create();
			if ($this->Sign->save($this->data)) {
				$this->Session->setFlash(__('The sign has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The sign could not be saved. Please, try again.', true));
			}
		}
		$people = $this->Sign->Person->find('list');
		$this->set(compact('people'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid sign', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Sign->save($this->data)) {
				$this->Session->setFlash(__('The sign has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The sign could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Sign->read(null, $id);
		}
		$people = $this->Sign->Person->find('list');
		$this->set(compact('people'));
	}

	function ultimosigno($id_signo = null, $id_paciente = null){
		if (!$id_signo) {
			return 0;
		}

		if ($id_paciente) {

			$peopleSigns = $this->PeopleSign->find('all', array(
							'conditions' => array(
												'PeopleSign.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
												'PeopleSign.person_id' => $id_paciente,
												'Sign.id' => $id_signo,
												'NOT' => array ('PeopleSign.staterecord_id' => array('2'))
											),
							'fields' => array('PeopleSign.valor, PeopleSign.fecha'),
							'order' => array('PeopleSign.fecha DESC, PeopleSign.created DESC'),
							'limit' => 1
			) );

			if(!empty($peopleSigns)){

				$arreglo['valor'] = $peopleSigns[0]['PeopleSign']['valor'];
				$arreglo['fecha'] = $peopleSigns[0]['PeopleSign']['fecha'];

				return $arreglo;
			}
		}
		// Si no tiene cargado ningun valor
		return array();
	}
}
?>